package com.learn.algorlthm;

import java.util.ArrayList;
import java.util.List;

/**
 * @classname:
 * @Description: 顺时针打印矩阵
 * @author: yfpu(fengpu.yang @ ucarinc.com)
 * @Date: 2018-07-31 11:41
 * 题目描述：
 * 输入一个矩阵，按照从外向里以顺时针的顺序依次打印出每一个数字，例如，
 * 如果输入如下4 X 4矩阵： 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
 * 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
 */
public class Learn29 {

    public static List<Integer> printMatrix() {
        int[][] matrix = getMatrix();

        int index = 0, top = 0, bottorm = matrix.length -1;
        int le = 0, ri = matrix[0].length - 1;
        boolean flag = true, isIncrease = true;
        List<Integer> ret = new ArrayList<>();

        while (flag) {
            int[] rowVal = matrix[index];

            if (index == top) {
                for (int i = le; i <= ri; i++) {
                    ret.add(rowVal[i]);
                }
            }else if(index == bottorm) {
                for (int i = ri; i >= le; i--) {
                    ret.add(rowVal[i]);
                }
            }else {
                if (isIncrease)
                    ret.add(rowVal[ri]);
                else
                    ret.add(rowVal[le]);
            }

            if (isIncrease) {
                if (index++ == bottorm) {
                    isIncrease = false;
                    ri--;
                    top++;
                    index = bottorm -1;
                }
            } else {
                if (index-- == top) {
                    isIncrease = true;
                    le++;
                    bottorm--;
                    index = top + 1;
                }
            }

            if (matrix.length % 2 == 0) {
                if (top == matrix.length / 2 && bottorm == matrix.length / 2)
                    flag = false;
            } else {
                if (top == matrix.length / 2 && bottorm == (top +1))
                    flag =false;
            }


        }

        return ret;
    }


    private static int[][] matrix = null;

    public static int[][] getMatrix() {
        if (matrix == null) {
            matrix = new int[4][5];
            int[] values = {1 ,2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 ,18, 19, 20};
            for (int i = 0; i < values.length; i++) {
                if (i < 5)
                    matrix[0][i] = values[i];
                else if (i < 10)
                    matrix[1][(i - 5)] = values[i];
                else if (i < 15)
                    matrix[2][(i - 10)] = values[i];
                else
                    matrix[3][(i - 15)] = values[i];

            }
        }
        return matrix;
    }
}
